package com.sl.auth.modular.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sl.auth.modular.login.entity.SaTokenDO;
import com.sl.auth.modular.login.mapper.SaTokenMapper;
import com.sl.auth.modular.login.service.SaTokenDaoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@RequiredArgsConstructor
public class SaTokenDaoServiceImpl extends ServiceImpl<SaTokenMapper, SaTokenDO> implements SaTokenDaoService {
    @Override
    public SaTokenDO getBySaKey(String key) {
        LambdaQueryWrapper<SaTokenDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SaTokenDO::getSaKey, key);
        return super.getOne(lambdaQueryWrapper);
    }

    @Override
    public Boolean updateValueByKey(String value, String key) {
        LambdaUpdateWrapper<SaTokenDO> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.eq(SaTokenDO::getSaKey, key);
        lambdaQueryWrapper.set(SaTokenDO::getSaValue, value);
        return super.update(lambdaQueryWrapper);
    }

    @Override
    public Boolean deleteByKey(String key) {
        LambdaQueryWrapper<SaTokenDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SaTokenDO::getSaKey, key);
        return super.remove(lambdaQueryWrapper);
    }

    @Override
    public Boolean updateTimeoutByKey(long timeout, String key) {
        LambdaUpdateWrapper<SaTokenDO> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.eq(SaTokenDO::getSaKey, key);
        lambdaQueryWrapper.set(SaTokenDO::getTimeout, timeout);
        return super.update(lambdaQueryWrapper);
    }

    @Override
    public List<SaTokenDO> queryValidKey() {

//        timeout<sysdate()-create_time and timeout!=-1
        LambdaUpdateWrapper<SaTokenDO> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.ne(SaTokenDO::getTimeout, " -1");
        //h2 datadiff
//        lambdaQueryWrapper.last(" and  timeout <  DATEDIFF('second', CURRENT_DATE,create_time) ");

        //mysql
        lambdaQueryWrapper.last(" and  timeout<sysdate()-create_time ");


//        lambdaQueryWrapper.set(SaTokenDO::getTimeout, timeout);
        return super.list(lambdaQueryWrapper);
    }

    @Override
    public List<SaTokenDO> queryBySearchKey(String keyword) {
        LambdaUpdateWrapper<SaTokenDO> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.likeRight(SaTokenDO::getSaKey, keyword);
        lambdaQueryWrapper.like(SaTokenDO::getSaKey, keyword);

        lambdaQueryWrapper.orderByDesc(SaTokenDO::getSaKey);
//        lambdaQueryWrapper.set(SaTokenDO::getTimeout, timeout);
        return super.list(lambdaQueryWrapper);
    }
}
